<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>涂色动作修复验证测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .test-section {
            background: rgba(255, 255, 255, 0.1);
            margin: 20px 0;
            padding: 20px;
            border-radius: 10px;
            backdrop-filter: blur(10px);
        }

        button {
            background: #4CAF50;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            margin: 5px;
        }

        button:hover {
            background: #45a049;
        }

        button:disabled {
            background: #666;
            cursor: not-allowed;
        }

        .log {
            background: rgba(0, 0, 0, 0.3);
            padding: 10px;
            border-radius: 5px;
            height: 400px;
            overflow-y: auto;
            font-family: monospace;
            font-size: 12px;
        }

        .input-group {
            margin: 10px 0;
        }

        .input-group label {
            display: block;
            margin-bottom: 5px;
        }

        .input-group input {
            width: 100%;
            padding: 8px;
            border: none;
            border-radius: 4px;
            margin-bottom: 10px;
        }

        .success {
            color: #4CAF50;
        }

        .error {
            color: #f44336;
        }

        .info {
            color: #2196F3;
        }

        .warning {
            color: #ff9800;
        }

        .debug {
            color: #9c27b0;
        }

        .grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }

        .status {
            padding: 10px;
            border-radius: 5px;
            margin: 10px 0;
        }

        .connected {
            background: rgba(76, 175, 80, 0.3);
            border: 1px solid #4CAF50;
        }

        .disconnected {
            background: rgba(244, 67, 54, 0.3);
            border: 1px solid #f44336;
        }

        .canvas-container {
            border: 2px solid #fff;
            border-radius: 10px;
            padding: 10px;
            background: rgba(255, 255, 255, 0.1);
        }

        canvas {
            border: 1px solid #ccc;
            background: white;
            cursor: crosshair;
        }
    </style>
</head>

<body>
    <h1>🎨 涂色动作修复验证测试</h1>

    <div class="test-section">
        <h2>🔧 修复内容</h2>
        <ul>
            <li>✅ 修复了前端涂色动作参数传递格式</li>
            <li>✅ 修复了后端PaintAction方法的详细错误处理</li>
            <li>✅ 添加了游戏状态检查逻辑</li>
            <li>✅ 实现了完整的StartGame功能</li>
            <li>✅ 添加了详细的调试日志输出</li>
        </ul>
    </div>

    <div class="grid">
        <div class="test-section">
            <h2>🔌 连接测试</h2>
            <div class="input-group">
                <label>房间码:</label>
                <input type="text" id="roomCode" value="TDJUCW" />
            </div>
            <div class="input-group">
                <label>玩家昵称:</label>
                <input type="text" id="playerName" value="测试玩家" />
            </div>
            <button onclick="testConnection()">连接并加入房间</button>
            <button onclick="disconnect()">断开连接</button>
            <div id="connectionStatus" class="status disconnected">未连接</div>
        </div>

        <div class="test-section">
            <h2>🎮 游戏功能测试</h2>
            <button onclick="testReadyFunction()" id="readyBtn" disabled>测试准备功能</button>
            <button onclick="testStartGame()" id="startBtn" disabled>测试开始游戏</button>
            <button onclick="testPaintAction()" id="paintBtn" disabled>测试涂色动作</button>
            <div id="gameStatus" class="status">未加入房间</div>
        </div>
    </div>

    <div class="test-section">
        <h2>🎨 涂色测试画布</h2>
        <div class="canvas-container">
            <canvas id="testCanvas" width="400" height="300"></canvas>
            <div style="margin-top: 10px;">
                <button onclick="clearCanvas()">清空画布</button>
                <button onclick="testDrawLine()">测试绘制线条</button>
                <button onclick="testDrawCircle()">测试绘制圆形</button>
            </div>
        </div>
    </div>

    <div class="test-section">
        <h2>📊 状态信息</h2>
        <div id="statusInfo"></div>
    </div>

    <div class="test-section">
        <h2>📝 实时日志</h2>
        <div id="log" class="log"></div>
        <button onclick="clearLog()">清空日志</button>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/6.0.1/signalr.min.js"></script>
    <script>
        let connection = null;
        let currentRoomCode = null;
        let currentPlayerName = null;
        let currentPlayerId = null;
        let isConnected = false;
        let gameStatus = 'waiting';
        let canvas = null;
        let ctx = null;
        let isDrawing = false;
        let lastX = 0;
        let lastY = 0;

        function log(message, type = 'info') {
            const logDiv = document.getElementById('log');
            const timestamp = new Date().toLocaleTimeString();
            const className = type;
            logDiv.innerHTML += `<div class="${className}">[${timestamp}] ${message}</div>`;
            logDiv.scrollTop = logDiv.scrollHeight;
        }

        function clearLog() {
            document.getElementById('log').innerHTML = '';
        }

        function updateConnectionStatus(connected) {
            const statusDiv = document.getElementById('connectionStatus');
            if (connected) {
                statusDiv.className = 'status connected';
                statusDiv.textContent = '已连接';
            } else {
                statusDiv.className = 'status disconnected';
                statusDiv.textContent = '未连接';
            }
            isConnected = connected;
        }

        function updateGameStatus(status) {
            document.getElementById('gameStatus').textContent = status;
            gameStatus = status;
        }

        function updateStatusInfo() {
            const statusDiv = document.getElementById('statusInfo');
            statusDiv.innerHTML = `
                <h3>当前状态</h3>
                <p><strong>连接状态:</strong> ${isConnected ? '已连接' : '未连接'}</p>
                <p><strong>房间码:</strong> ${currentRoomCode || '未设置'}</p>
                <p><strong>玩家昵称:</strong> ${currentPlayerName || '未设置'}</p>
                <p><strong>玩家ID:</strong> ${currentPlayerId || '未设置'}</p>
                <p><strong>游戏状态:</strong> ${gameStatus}</p>
                <p><strong>连接对象:</strong> ${connection ? '存在' : '不存在'}</p>
                <p><strong>连接状态:</strong> ${connection?.state || '未知'}</p>
            `;
        }

        function enableButtons() {
            document.getElementById('readyBtn').disabled = false;
            document.getElementById('startBtn').disabled = false;
            document.getElementById('paintBtn').disabled = false;
        }

        function initCanvas() {
            canvas = document.getElementById('testCanvas');
            ctx = canvas.getContext('2d');

            // 设置画布背景
            ctx.fillStyle = '#ffffff';
            ctx.fillRect(0, 0, canvas.width, canvas.height);

            // 设置绘图样式
            ctx.strokeStyle = '#FF0000';
            ctx.lineWidth = 5;
            ctx.lineCap = 'round';
            ctx.lineJoin = 'round';

            // 添加鼠标事件
            canvas.addEventListener('mousedown', startDrawing);
            canvas.addEventListener('mousemove', draw);
            canvas.addEventListener('mouseup', stopDrawing);
            canvas.addEventListener('mouseout', stopDrawing);
        }

        function startDrawing(event) {
            isDrawing = true;
            const rect = canvas.getBoundingClientRect();
            lastX = event.clientX - rect.left;
            lastY = event.clientY - rect.top;

            ctx.beginPath();
            ctx.moveTo(lastX, lastY);
        }

        function draw(event) {
            if (!isDrawing) return;

            const rect = canvas.getBoundingClientRect();
            const x = event.clientX - rect.left;
            const y = event.clientY - rect.top;

            ctx.lineTo(x, y);
            ctx.stroke();

            // 发送涂色动作
            if (isConnected && currentRoomCode && currentPlayerId) {
                submitPaintAction(currentRoomCode, currentPlayerId, Math.round(x), Math.round(y), 5);
            }

            lastX = x;
            lastY = y;
        }

        function stopDrawing() {
            isDrawing = false;
            ctx.closePath();
        }

        function clearCanvas() {
            ctx.fillStyle = '#ffffff';
            ctx.fillRect(0, 0, canvas.width, canvas.height);
        }

        function testDrawLine() {
            ctx.beginPath();
            ctx.moveTo(50, 50);
            ctx.lineTo(350, 250);
            ctx.stroke();
        }

        function testDrawCircle() {
            ctx.beginPath();
            ctx.arc(200, 150, 50, 0, Math.PI * 2);
            ctx.fillStyle = '#FF0000';
            ctx.fill();
        }

        async function testConnection() {
            try {
                const url = 'http://localhost:5152/gamehub';
                log(`正在连接SignalR: ${url}`, 'info');

                connection = new signalR.HubConnectionBuilder()
                    .withUrl(url)
                    .withAutomaticReconnect([0, 2000, 10000, 30000])
                    .build();

                // 设置事件处理器
                connection.on('PlayerJoined', (player) => {
                    log(`玩家加入: ${player.nickName || player.NickName}`, 'success');
                });

                connection.on('PlayerLeft', (playerId) => {
                    log(`玩家离开: ${playerId}`, 'warning');
                });

                connection.on('PlayerReady', (playerId, ready) => {
                    log(`玩家准备状态: ${playerId} = ${ready}`, 'info');
                });

                connection.on('GameStarted', (gameData) => {
                    log(`游戏开始: ${JSON.stringify(gameData)}`, 'success');
                    updateGameStatus('playing');
                });

                connection.on('PaintActionReceived', (action) => {
                    log(`收到涂色动作: ${JSON.stringify(action)}`, 'info');
                });

                connection.on('Error', (error) => {
                    log(`错误: ${error}`, 'error');
                });

                await connection.start();
                updateConnectionStatus(true);
                log('SignalR连接成功', 'success');

                // 加入房间
                currentRoomCode = document.getElementById('roomCode').value;
                currentPlayerName = document.getElementById('playerName').value;

                log(`加入房间: ${currentRoomCode}, 玩家: ${currentPlayerName}`, 'info');
                await connection.invoke('JoinGame', currentRoomCode, currentPlayerName, null);
                updateGameStatus('已加入房间');
                log('成功加入房间', 'success');

                enableButtons();
                updateStatusInfo();
            } catch (error) {
                log(`连接失败: ${error.message}`, 'error');
                updateConnectionStatus(false);
            }
        }

        async function disconnect() {
            if (connection) {
                try {
                    await connection.stop();
                    connection = null;
                    updateConnectionStatus(false);
                    updateGameStatus('已断开连接');
                    log('已断开连接', 'info');

                    // 禁用按钮
                    document.getElementById('readyBtn').disabled = true;
                    document.getElementById('startBtn').disabled = true;
                    document.getElementById('paintBtn').disabled = true;
                } catch (error) {
                    log(`断开连接失败: ${error.message}`, 'error');
                }
            }
        }

        async function testReadyFunction() {
            if (!isConnected) {
                log('未连接到服务器', 'error');
                return;
            }

            try {
                log('测试准备功能...', 'info');
                await connection.invoke('SetReady', currentRoomCode, currentPlayerName, true);
                log('✅ 准备功能测试成功', 'success');
            } catch (error) {
                log(`❌ 准备功能测试失败: ${error.message}`, 'error');
            }
        }

        async function testStartGame() {
            if (!isConnected) {
                log('未连接到服务器', 'error');
                return;
            }

            try {
                log('测试开始游戏...', 'info');
                await connection.invoke('StartGame', currentRoomCode);
                log('✅ 开始游戏测试成功', 'success');
            } catch (error) {
                log(`❌ 开始游戏测试失败: ${error.message}`, 'error');
            }
        }

        async function testPaintAction() {
            if (!isConnected) {
                log('未连接到服务器', 'error');
                return;
            }

            try {
                log('测试涂色动作...', 'info');
                await submitPaintAction(currentRoomCode, currentPlayerName, 100, 100, 5);
                log('✅ 涂色动作测试成功', 'success');
            } catch (error) {
                log(`❌ 涂色动作测试失败: ${error.message}`, 'error');
            }
        }

        async function submitPaintAction(roomCode, playerId, x, y, brushSize) {
            try {
                log(`提交涂色动作: roomCode=${roomCode}, playerId=${playerId}, x=${x}, y=${y}, brushSize=${brushSize}`, 'debug');
                await connection.invoke('PaintAction', roomCode, playerId, x, y, brushSize);
                log('涂色动作提交成功', 'success');
            } catch (error) {
                log(`涂色动作提交失败: ${error.message}`, 'error');
                throw error;
            }
        }

        // 页面加载时初始化
        window.onload = function () {
            log('涂色动作修复验证测试页面已加载', 'info');
            log('请确保后端服务在 http://localhost:5152 运行', 'warning');
            initCanvas();
            updateStatusInfo();
        };
    </script>
</body>

</html>